#!/usr/bin/env bash

#   include libs
#   init args
set -u
readonly CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
source "${CUR_DIR}"/lib/lib.sh
readonly YEAR=$(date +%Y)
readonly MON=$(date +%m)
readonly DAY=$(date +%d)

readonly XUNJIAN="${CUR_DIR}/xunjian"
readonly CONFIG_DIR="${CUR_DIR}/config"
readonly LOG_DIR="${CUR_DIR}/log"
readonly EXP_DIR="${CUR_DIR}/exp"
readonly PY_DIR="${CUR_DIR}/py_script"

readonly SW_DIR="${CONFIG_DIR}/sws"
readonly SERVER_DIR="${CONFIG_DIR}/servers"

readonly SW_CONFIG="${SW_DIR}/sw_info.txt"
readonly SERV_CONFIG="${SERVER_DIR}/server_info.txt"
readonly LOG_FILE="${LOG_DIR}/log.txt"
readonly EXP_SCRIPT="${EXP_DIR}/sw_expect.exp"
readonly PY_FILE="${PY_DIR}/general_report.py"
readonly XUNJIAN_DIR="${XUNJIAN}/${YEAR}/${MON}"

cleanup() {
	rm -f ${CUR_DIR}/check.lock
	exit 0
}

check_lock() {
	if [ -e ${CUR_DIR}/check.lock ]; then
		exit 1
	fi
	touch ${CUR_DIR}/check.lock
	trap cleanup EXIT TERM INT
}

#   touch dirs  log / xunjian /
touch_dirs(){
    declare -i ret=1
    ret=$(mk_dir "${LOG_DIR}")
    if ! [ $ret -eq 0 ]; then
        echo "Create log directory failed,script exit"
        exit 1
    fi
    ret=$(mk_dir "${XUNJIAN_DIR}")
    if ! [ $ret -eq 0 ]; then
        echo "Create xunjian directory failed,script exit"
        log "${LOG_FILE}" "Create 'xunjian' directory failed,script exit" 2
        exit 1
    fi
}
#   check config files
check_config_file(){
    if ! ( [ -e ${SW_CONFIG} ]); then
        echo "missing ${SW_CONFIG}"
        log "${LOG_FILE}" "missing ${SW_CONFIG}" 2
        exit 1
    fi
    if ! ( [ -e ${SERV_CONFIG} ]); then
        echo "missing ${SERV_CONFIG}"
        log "${LOG_FILE}" "missing ${SERV_CONFIG}" 2
        exit 1
    fi
    if ! ( [ -e ${EXP_SCRIPT} ]); then
        echo "missing ${EXP_SCRIPT}"
        log "${LOG_FILE}" "${EXP_SCRIPT}" 2
        exit 1
    fi
}

#create the log dir/xunjian dir/

inspect_sws(){
    while IFS=',' read -r device_name device_ip protocal user passwd;do
        device_name=$(echo "$device_name" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        device_ip=$(echo "$device_ip" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        protocal=$(echo "$protocal" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        user=$(echo "$user" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        passwd=$(echo "$passwd" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        #   continue when blank
        #   continue when met '#'
        if [ -z ${device_name} ] || [[ ${device_name} =~ ^#.* ]] ;then
            continue
        fi
        #   make the csv file
        #   touch when no exist , build the title
        csv_file="${XUNJIAN_DIR}/${device_name}.csv"
        sw_config="${SW_DIR}/${device_name}"
        if ! [ -e "${csv_file}" ];then
            touch "${csv_file}"
            if ! [ $? -eq 0 ];then
                echo "Create ${csv_file} failed";
                log "${LOG_FILE}" "Create ${csv_file} failed" 1
                continue
            fi
            titles=$(cat "${sw_config}"|cut -d, -f1)
            content="巡检时间"
            for title in $titles;do
                title=$(echo "${title}"|sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
                if [ -z "${title}" ] || [[ "${title}" =~ ^#.* ]]; then
                    continue;
                fi
                content="${content},${title}"
            done
            echo "${content}" > "${csv_file}"
        fi

        #   do exp_script
        args=()
        args+=("${protocal}")
        args+=("${device_ip}")
        args+=("${user}")
        args+=("${passwd}")
        while IFS=',' read -r foo cmd reg;do
            cmd=$(echo "$cmd" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
            reg=$(echo "$reg" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
            if [ -z "${foo}" ];then
                continue
            fi
            args+=("${cmd}")
            args+=("${reg}")
        done < "${sw_config}"

        check_info=$(expect "${EXP_SCRIPT}" "${args[@]}")
        if ! [ $? -eq 0 ]; then
            log "${LOG_FILE}" "expect script go wrong with ${device_name}" 1
        fi
        echo "$(date '+%Y-%m-%d %H:%M:%S')${check_info}" >> "${csv_file}"
    done < "${SW_CONFIG}"
}

inspect_servers(){
    while read -r server_name snmp_version server_ip community ; do
        server_name=$(echo ${server_name}|xargs)
        snmp_version=$(echo ${snmp_version}|xargs)
        server_ip=$(echo ${server_ip}|xargs)
        community=$(echo ${community}|xargs)

        # continue when start with # or blank line
        if [[ ${server_name} =~ ^#.* ]] || [ -z ${server_name} ];then
            continue
        fi
        check_info=$(now)
        while IFS=',' read -r s_title s_oid s_cmd; do
            s_title=$(echo ${s_title}|xargs)
            s_oid=$(echo ${s_oid}|xargs)
            ## xargs will swallow the ' sign
            s_cmd=$(echo "${s_cmd}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' )
            if [[ -z "${s_title}" || "${s_title}" =~ ^#.* ]]; then
                continue
            fi
            csv_file="${XUNJIAN_DIR}/${server_name}.csv"
            if ! [ -e "${csv_file}" ]; then
                touch "${csv_file}"
                content=$(cat "${SERVER_DIR}/${server_name}"|cut -d, -f1)
                title="巡检时间"
                while IFS= read -r line; do
                    line=$(echo "${line}"|xargs)
                    title="${title},${line}"
                done < <(echo "${content}")
                echo "${title}" > ${csv_file}
            fi
            snmp_ret=$(snmpwalk -t 4 -r 1 -v "${snmp_version}" -c "${community}" "${server_ip}" "${s_oid}" 2>/dev/null)
            if ! [ $? -eq 0 ] ; then
                snmp_ret=""
                log "${LOG_FILE}" "${server_name} failed :snmpwalk -v ${snmp_version} -c ${community} ${server_ip} ${s_oid}" 1
            else
                snmp_ret=$(echo "${snmp_ret}" | eval "${s_cmd}" | xargs)
            fi
            if [ -z "${snmp_ret}" ]; then
                snmp_ret="-"
            fi
            check_info="${check_info},${snmp_ret}"
        done < "${SERVER_DIR}/${server_name}"
        echo "${check_info}" >> "${csv_file}"
    done < "${SERV_CONFIG}"
}

main (){
	check_lock
    touch_dirs
    check_config_file
    echo "开始巡检 $(date '+%Y-%m-%d %H:%M:%S')"
    log "${LOG_FILE}" "开始巡检" 0
    inspect_sws
    inspect_servers
    echo "结束巡检 $(date '+%Y-%m-%d %H:%M:%S')"
    log "${LOG_FILE}" "结束巡检" 0
	python "${PY_FILE}"
}

main "$@"

#exist_or_touch (){
#	if [ -e $1 ]; then
#		return 0
#	else
#		touch "$1"
#		return $?
#	fi
#}

